<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebWorkerDemo</title>
</head>
<body>

<script>
    var worker = new Worker('js/work.js')

    //主线程发送数据
    worker.postMessage('Hello World');
    worker.postMessage({method: 'echo', args: ['Work']});

    //主线程接收数据
    worker.onmessage = function (event) {
        console.log('Received message ' + event.data);

        //任务
        doSomething();

        console.log(worker)
    }

    //接收到数据后执行任务
    function doSomething() {
        // 执行任务
        worker.postMessage('Work done!');

        //执行任务后结束worker
        worker.terminate();
    }

    //监听是否发生错误
    worker.onerror = function (e) {
        console.log([
            'ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message
        ].join(''));
    };

</script>
</body>
</html>
